import React, { useState, useEffect, useRef } from 'react'
import { Uploader } from 'react-vant'
import './style.less'
import add_css from './add_hand.module.css'
import { BrowserRouter as Router, Route, Routes, useNavigate } from 'react-router-dom'
import axios from 'axios'
// 上传图片tdesign@ts-ignore
import { Upload, MessagePlugin } from 'tdesign-react';
import { getFileUrlByFileRaw } from 'tdesign-react/es/_common/js/upload/utils';
// 
import { Picker, Toast } from 'react-vant'
export default function Add_hand() {
    const navigate = useNavigate()
    const [type, setType] = useState([])
    const getsecond_type = () => {
        axios.get(`http://localhost:3000/secondType`).then(res => {
            let { code, data } = res.data
            if (code == 200) {
                setType(data)
            }
        })
    }
    let [url, setUrl] = useState([])
    let [second_name, setsecond_name] = useState('')
    let [ni_name, setNi_name] = useState('')
    let [img_head, setImg_head] = useState('')
    let [content, setContent] = useState('')
    let [secondType_name, setsecondType_name] = useState('')
    // 上传图片
    const uploadRef3 = useRef(null);
    const [files3, setFiles3] = useState([]);
    const [disabled, setDisabled] = useState(false);
    const [autoUpload, setAutoUpload] = useState(true);
    // 帖子图片
    let [imgs, setImgs] = useState([])
    const add_hhh = () => {
        let from = {
            second_name: second_name, img: imgs, is_sell: true, img_head: '',
            ni_name: ni_name, content: content, secondType_name: secondType_name
        }
        console.log(from);
        axios.post('http://localhost:3000/add_homeAppliances',from).then(res=>{
            let {code,msg}=res.data
            if(code==200){
                navigate('/secondHand')
            }
        })
    }
    const setFormattedUrlFiles = (files) => {
        const list = files.map(
            (file) =>
                new Promise((resolve) => {
                    getFileUrlByFileRaw(file.raw).then((url) => {
                        resolve({
                            ...file,
                            url,
                        });
                    });
                }),
        );
        Promise.all(list).then((files) => {
            setFiles3(files);
            console.log(files, 'files');
            // 提取本次上传成功的图片的URL地址，并进行去重处理后添加到imgs数组
            const newUrls = files.map((file) => file.url);
            const uniqueUrls = [];
            newUrls.forEach((url) => {
                if (!imgs.includes(url) && !uniqueUrls.includes(url)) {
                    uniqueUrls.push(url);
                }
            });
            setImgs((prevUrls) => [...prevUrls, ...uniqueUrls]);
        });
    };
    const [uploadInOneRequest, setUploadInOneRequest] = useState(false);
    // 因上传请求始终返回固定的 url，为了让预览效果更加真实，故而将图片转为 base64 进行预览
    const onSuccess = ({ currentFiles }) => {
        const files = autoUpload ? files3.concat(currentFiles) : currentFiles;
        setFormattedUrlFiles(files);
    };
    // 有文件数量超出时会触发，文件大小超出限制、文件同名时会触发等场景。注意如果设置允许上传同名文件，则此事件不会触发
    const onValidate = (params) => {
        const { files, type } = params;
        console.log('onValidate', params);
        if (type === 'FILE_OVER_SIZE_LIMIT') {
            files.map((t) => t.name).join('、');
            MessagePlugin.warning(`${files.map((t) => t.name).join('、')} 等图片大小超出限制，已自动过滤`, 8000);
        } else if (type === 'FILES_OVER_LENGTH_LIMIT') {
            MessagePlugin.warning('文件数量超出限制，仅上传未超出数量的文件');
        } else if (type === 'FILTER_FILE_SAME_NAME') {
        }
    }
    // 如果希望支持上传
    useEffect(() => {
        getsecond_type()
    }, [])
    return (
        <div>
            <nav className={add_css.main}>
                <div className={add_css.header}>
                    <span style={{ color: 'skyblue', fontSize: '6vw' }} onClick={() => { navigate('/secondHand') }}>取消</span>
                    <span style={{ fontSize: '7vw', marginLeft: '-7vw' }}>我要出售</span>
                    <span></span>
                </div>
                <div>
                    {/* <input type="color" name="" id=""/> */}
                    <div className={add_css.addlis}>
                        <div className={add_css.addlisone}>
                            <span>二手家电名称</span>
                            <input type="text" value={second_name} onChange={(e) => {setsecond_name(e.target.value) }} placeholder='请输入名称' />
                        </div>
                        <div className={add_css.addlisone}>
                            <span>二手家电类别</span>
                            <select value={secondType_name} onChange={(e) => { setsecondType_name(e.target.value) }}>
                                <option value="">请选择</option>
                                {type.map((item, index) => {
                                    return <option key={item._id} value={item._id}>{item.name}</option>
                                })}
                            </select>
                        </div>
                    </div>
                    <div className={add_css.addlists}>
                        <div className={add_css.addlistwo}>
                            <span>上传图片</span>
                            <Upload
                                ref={uploadRef3}
                                files={files3}
                                onChange={setFiles3}
                                action="//service-bv448zsw-1257786608.gz.apigw.tencentcs.com/api/upload-demo"
                                theme="image"
                                // tips="允许选择多张图片文件上传，最多只能上传 3 张图片"
                                accept="image/*"
                                multiple
                                max={3}
                                disabled={disabled}
                                sizeLimit={{
                                    size: 2,
                                    unit: 'MB',
                                }}
                                autoUpload={autoUpload}
                                abridgeName={[6, 6]}
                                uploadAllFilesInOneRequest={uploadInOneRequest}
                                onSuccess={onSuccess}
                                onValidate={onValidate}
                                // onPreview={onPreview}
                                showImageFileName={false}
                            />
                        </div>
                        <div className={add_css.addlistwo}>
                            <span>用户头像</span>

                        </div>
                    </div>
                    <div className={add_css.addlis}>
                        <div className={add_css.addlisone}>
                            <span>用户昵称</span>
                            <input type="text" value={ni_name} onChange={(e ) => {setNi_name(e.target.value) }} placeholder='输入昵称' />
                        </div>
                        <div className={add_css.addlisonea}>
                            <span>家电描述</span>
                            <textarea value={content} onChange={e => { setContent(e.target.value) }} cols="30" rows="6"></textarea>
                        </div>
                    </div>
                    <div className={add_css.buts}>
                        <button onClick={() => { add_hhh() }}>确认出售</button>
                    </div>
                </div>
            </nav>
        </div>
    )
}
